#!/usr/bin/perl
use lib "$ENV{MYSQL_DRAW}/lib";
use MyTools;
use strict;
use Data::Dumper;
use Getopt::Long;
use DBI;

my ($project_name, $flowcell_name, $ref_genome, $dbsnp, $target_intervals, $user_id, $debug);
my @argv = @ARGV;
&GetOptions("debug!"=> \$debug,
            "project_name=s" => \$project_name,
            "flowcell_name=s" => \$flowcell_name,
            "ref_genome=s" => \$ref_genome,
            "dbsnp=i" => \$dbsnp,
            "target_intervals=s" => \$target_intervals,
            "user_id=i" => \$user_id);

if ((!$project_name) || (!$flowcell_name) || (!$ref_genome) || (!$dbsnp) || (!$user_id)) {
	die "usage: $0 --project_name PSP --flowcell_name Project_50260 --ref_genome hg19 --dbsnp 135 --target_intervals NIMBLGEN --user_id 6 [--debug]\n(use --debug to preview what would be inserted into mysql table)\n";
}

my $table = `basename $0 .pl | sed s/insert//`;
chomp($table);
if ($debug) {
	print Dumper(@argv);
}
else {
	my $newid=driver();
	printf STDERR "${project_name}_${flowcell_name} %s\n", ($newid) ? "inserted into $table with DRID=$newid" : "already in $table";
}

sub driver {
	my $dbh = DBI->connect($ENV{dbi1}, $ENV{dbi2}, $ENV{dbi3}) or die "Couldn't connect to database: " . DBI->errstr;;
	my $project_id = MyTools::fetchrow1col1_arrayref($dbh, "select PID from Project where ", {'ProjectName' => $project_name}) or die "Project $project_name not found\n";
	my $flowcell_id = MyTools::fetchrow1col1_arrayref($dbh, "select FID from Flowcell where ", {'FlowcellName' => $flowcell_name}) or die "Flowcell $flowcell_name not found\n";
	my $record_present = MyTools::fetchrow1col1_arrayref($dbh, "select DRID from $table where ", {'ProjectID' => $project_id, 'FlowcellID' => $flowcell_id});
	return 0 if (defined($record_present));
	my $sth = $dbh->prepare("INSERT INTO $table (ProjectID,FlowcellID,RunName,RefGenome,dbSNP,TargetIntervals,UserID) VALUES (?,?,?,?,?,?,?)") or die "Couldn't prepare statement: " . $dbh->errstr;
	$sth->execute($project_id, $flowcell_id, "${project_name}_${flowcell_name}", $ref_genome, $dbsnp, $target_intervals, $user_id) or die "Couldn't execute statement: " . $sth->errstr;
	return MyTools::fetchrow1col1_arrayref($dbh, "select DRID from $table where ", {'ProjectID' => $project_id, 'FlowcellID' => $flowcell_id});
}
